<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Taxonomy extends Eloquent
{
	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'taxonomy';
	protected $validator = null;
	protected $hidden = array('created_at', 'updated_at', 'deleted_at', 'type', 'order');

	public function saveData($data)
	{
		$brand = new Taxonomy;

		if(isset($data['id'])){
			$brand = Taxonomy::firstOrCreate(array('id' => $data['id']));
		}
		
		$brand->taxonomy = $data['taxonomy'];
		$brand->order    = $data['order'];
		$brand->type     = $data['type'];
		$brand->save();

		return $brand;
	}

	public function getDatas($page = 0, $limit = 10)
	{
		$brands = Taxonomy::all();

		return $brands;
	}

	public function scopeBrands($query){
		return $query->whereType('brand')->orderBy('order')->get();
	}

	public function scopeBrandsToDropdownList($query){
		$result = $query->whereType('brand')->orderBy('order')->get()->toArray();

		$brands = array();

		foreach($result as $row){
			$brands[$row['id']] = $row['taxonomy'];
		}

		return $brands;
	}

	public function scopeTypes($query){
		return $query->whereType('type')->orderBy('order')->get();
	}

	public function scopeTypesToDropdownList($query){
		$result = $query->whereType('type')->orderBy('order')->get()->toArray();

		$types = array();

		foreach($result as $row){
			$types[$row['id']] = $row['taxonomy'];
		}

		return $types;
	}

	public function validator($data)
	{
		$id = (isset($data['id']))? $data['id'] : "NULL";

		$rules = array(
				'taxonomy' => 
					array(
						'required', 
						'unique:taxonomy,taxonomy,' . $id . ',id,type,' . $data['type'] . ',deleted_at,NULL',
						'alpha_num_spaces',
					),
				'order' => 
					array(
						'required', 
						'min:0', 
						'numeric',
					),
				);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getValidatorMessage(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}